﻿using System;
using Orchard.Tokens;
using Orchard.Localization;
using Orchard.ContentManagement;
using Orchard.Autoroute.Models;
using Orchard.Taxonomies.Models;
using Orchard.Taxonomies.Services;

namespace IvyExcellence.HierarchicalUrls.Tokens
{
    public class SlugTokens : ITokenProvider
    {
        private readonly ITaxonomyService _taxonomyService;

        public SlugTokens(ITaxonomyService taxonomyService)
        {
            _taxonomyService = taxonomyService;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        public void Describe(DescribeContext context)
        {
            context.For("Content")
                .Token("Path", T("Path"), T("The full path of an item as already generated by Autoroute"));
        }

        public void Evaluate(EvaluateContext context)
        {
            context.For<IContent>("Content").Token("Path", (content =>
            {
                var autoroutePart = content.As<AutoroutePart>();
                if (autoroutePart == null)
                {
                    return String.Empty;
                }

                var taxonomy = content.ContentItem.As<TaxonomyPart>();
                if (taxonomy != null)
                {
                    var channelsTaxonomy = _taxonomyService.GetTaxonomyByName("Channels");
                    if (channelsTaxonomy != null)
                    {
                        if (taxonomy.TermTypeName.Equals(channelsTaxonomy.TermTypeName))
                        {
                            return String.Empty;
                        }
                    }
                }

                return autoroutePart.DisplayAlias;
            }));
        }
    }
}
